"""
Web管理界面路由
提供基于Jinja2模板的Web界面路由
"""
from fastapi import APIRouter, Request, Depends, Form
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from typing import Optional, Dict, Any
import json
import time
from datetime import datetime
from enum import Enum

from core.auth import get_current_user, require_admin, get_current_user_from_token
from core.config import settings
from core.database import get_db
from core.logging_config import get_logger
from models.user import User
from models.analysis_task import AnalysisTask, TaskStatus
from models.data_source import DataSource
from models.report import Report
from sqlalchemy.orm import Session
from sqlalchemy import func, desc, and_, or_
from fastapi import HTTPException, status

# 创建路由器
web_router = APIRouter()

# 获取日志记录器
logger = get_logger("web_routes")

# 设置Jinja2模板
jinja_templates = Jinja2Templates(directory="templates")

# 通用上下文数据
def get_common_context(request: Request, current_user: User = None) -> Dict[str, Any]:
    """获取通用模板上下文数据"""
    return {
        "request": request,
        "current_user": current_user,
        "app_name": settings.app_name,
        "app_version": settings.app_version,
        "now": datetime.now(),
        "debug": settings.debug,
        "config": {"DEBUG": settings.debug}  # 添加config对象以兼容模板
    }


async def get_web_current_user(request: Request, db: Session = Depends(get_db)) -> Optional[User]:
    """获取Web界面的当前用户（基于JWT令牌）"""
    # 首先尝试从Authorization头获取令牌
    auth_header = request.headers.get("Authorization")
    token = None
    
    if auth_header and auth_header.startswith("Bearer "):
        token = auth_header.split(" ")[1]
    else:
        # 如果Authorization头中没有，尝试从cookie中获取
        token = request.cookies.get("auth_token")
    
    if not token:
        return None
    
    try:
        # 使用新的token验证函数
        user = get_current_user_from_token(token, db)
        return user
    except Exception as e:
        print(f"Token验证失败: {e}")
        return None


async def get_web_user_or_redirect(request: Request, db: Session = Depends(get_db)) -> Optional[User]:
    """获取Web用户或重定向到登录页"""
    user = await get_web_current_user(request, db)
    if user is None:
        return None
    return user




@web_router.get("/login", response_class=HTMLResponse)
async def login_page(request: Request):
    """登录页面"""
    context = get_common_context(request)
    return jinja_templates.TemplateResponse("login.html", context)


@web_router.post("/login", response_class=HTMLResponse)
async def login_action(
    request: Request,
    username: str = Form(...),
    password: str = Form(...),
    db: Session = Depends(get_db)
):
    """登录处理"""
    context = get_common_context(request)
    
    try:
        # 查找用户
        user = db.query(User).filter(
            User.username == username,
            User.is_active == True,
            User.is_deleted == False
        ).first()
        
        if not user or not user.verify_password(password):
            context.update({
                "error": "用户名或密码错误"
            })
            return jinja_templates.TemplateResponse("login.html", context)
        
        # 更新登录信息
        user.update_login_info()
        db.commit()
        
        # 创建JWT令牌
        from core.auth import create_access_token
        from datetime import timedelta
        access_token = create_access_token(
            data={"sub": user.username, "user_id": user.id},
            expires_delta=timedelta(minutes=30)
        )
        
        # 创建重定向响应
        response = RedirectResponse(url="/web/analysis-results", status_code=303)
        
        # 设置JWT令牌在cookie中
        response.set_cookie(
            key="auth_token",
            value=access_token,
            httponly=False,  # 允许JavaScript访问
            max_age=1800,  # 30分钟
            secure=False,  # 在开发环境中设置为False，生产环境应该设置为True
            samesite="lax"
        )
        
        return response
        
    except Exception as e:
        context.update({
            "error": f"登录失败: {str(e)}"
        })
        return jinja_templates.TemplateResponse("login.html", context)


@web_router.get("/logout", response_class=HTMLResponse)
async def logout_page():
    """登出页面"""
    response = RedirectResponse(url="/web/login", status_code=303)
    # 清除JWT令牌cookie
    response.delete_cookie("auth_token")
    # 清除refresh_token cookie（如果存在）
    response.delete_cookie("refresh_token")
    return response


@web_router.get("/analysis-results", response_class=HTMLResponse)
async def analysis_results_page(
    request: Request,
    db: Session = Depends(get_db),
    page: int = 1,
    page_size: int = 20,
    task_type: Optional[str] = None,
    status: Optional[str] = None
):
    """分析结果页面"""
    # 获取当前用户
    current_user = await get_web_current_user(request, db)
    if current_user is None:
        return RedirectResponse(url="/web/login", status_code=303)
    
    context = get_common_context(request, current_user)
    
    try:
        # 构建查询
        query = db.query(AnalysisTask)
        
        if task_type:
            query = query.filter(AnalysisTask.task_type == task_type)
        if status:
            query = query.filter(AnalysisTask.status == status)
        
        # 获取总数
        total = query.count()
        
        # 分页查询
        tasks = query.order_by(desc(AnalysisTask.created_at)).offset(
            (page - 1) * page_size
        ).limit(page_size).all()
        
        context.update({
            "tasks": tasks,
            "total": total,
            "page": page,
            "page_size": page_size,
            "total_pages": (total + page_size - 1) // page_size,
            "task_type": task_type,
            "status": status,
            "task_status_choices": [status.value for status in TaskStatus],
            "timestamp": int(time.time())
        })
        
    except Exception as e:
        context.update({
            "error": f"获取分析结果失败: {str(e)}"
        })
    
    return jinja_templates.TemplateResponse("analysis-results.html", context)


@web_router.get("/petition-ledger", response_class=HTMLResponse)
async def petition_ledger_page(
    request: Request,
    db: Session = Depends(get_db)
):
    """信访台账页面"""
    # 获取当前用户
    current_user = await get_web_current_user(request, db)
    if current_user is None:
        return RedirectResponse(url="/web/login", status_code=303)

    context = get_common_context(request, current_user)

    # 添加页面特定配置
    context.update({
        "page_config": {
            "title": "信访台账",
            "description": "综合查询与分析结果展示",
            "features": {
                "advanced_search": True,
                "export": True,
                "pagination": True,
                "details_view": True
            }
        }
    })

    return jinja_templates.TemplateResponse("petition-ledger/list.html", context)


@web_router.get("/petition-ledger/{record_id}", response_class=HTMLResponse)
async def petition_ledger_detail_page(
    request: Request,
    record_id: int,
    db: Session = Depends(get_db)
):
    """信访台账详情页面"""
    # 获取当前用户
    current_user = await get_web_current_user(request, db)
    if current_user is None:
        return RedirectResponse(url="/web/login", status_code=303)

    context = get_common_context(request, current_user)

    # 添加页面特定配置和记录ID
    context.update({
        "page_config": {
            "title": "信访台账详情",
            "description": "多维度分析结果展示",
            "features": {
                "export": True,
                "print": True,
                "map_view": True,
                "charts": True
            }
        },
        "record_id": record_id
    })

    return jinja_templates.TemplateResponse("petition-ledger/detail.html", context)




@web_router.get("/ai-analysis", response_class=HTMLResponse)
async def ai_analysis_page(
    request: Request,
    db: Session = Depends(get_db)
):
    """AI分析管理页面"""
    # 获取当前用户
    current_user = await get_web_current_user(request, db)
    if current_user is None:
        return RedirectResponse(url="/web/login", status_code=303)
    
    context = get_common_context(request, current_user)
    
    try:
        # 获取数据源
        data_sources = db.query(DataSource).filter(
            DataSource.is_active == True
        ).all()
        
        # 获取任务模板
        from models.analysis_task import TaskTemplate
        task_templates = db.query(TaskTemplate).filter(
            TaskTemplate.is_active == True
        ).all()
        
        context.update({
            "data_sources": data_sources,
            "task_templates": task_templates
        })
        
    except Exception as e:
        context.update({
            "error": f"获取AI分析数据失败: {str(e)}"
        })
    
    return jinja_templates.TemplateResponse("ai-analysis/index.html", context)


@web_router.get("/regional-analysis", response_class=HTMLResponse)
async def regional_analysis_page(
    request: Request,
    db: Session = Depends(get_db)
):
    """区域分析页面"""
    # 获取当前用户
    current_user = await get_web_current_user(request, db)
    if current_user is None:
        return RedirectResponse(url="/web/login", status_code=303)
    
    context = get_common_context(request, current_user)
    
    try:
        # 获取区域统计数据
        # 这里需要根据实际的数据模型来查询
        context.update({
            "regions": [],
            "chart_data": {}
        })
        
    except Exception as e:
        context.update({
            "error": f"获取区域分析数据失败: {str(e)}"
        })
    
    return jinja_templates.TemplateResponse("regional-analysis.html", context)


@web_router.get("/complaint-analysis", response_class=HTMLResponse)
async def complaint_analysis_page(
    request: Request,
    db: Session = Depends(get_db)
):
    """投诉类型分析页面"""
    # 获取当前用户
    current_user = await get_web_current_user(request, db)
    if current_user is None:
        return RedirectResponse(url="/web/login", status_code=303)

    context = get_common_context(request, current_user)

    try:
        # 获取投诉类型统计数据
        # 这里需要根据实际的数据模型来查询
        context.update({
            "complaint_types": [],
            "chart_data": {}
        })

    except Exception as e:
        context.update({
            "error": f"获取投诉类型分析数据失败: {str(e)}"
        })

    return jinja_templates.TemplateResponse("complaint-analysis.html", context)


@web_router.get("/sentiment-analysis", response_class=HTMLResponse)
async def sentiment_analysis_page(
    request: Request,
    db: Session = Depends(get_db)
):
    """情感分析页面"""
    # 获取当前用户
    current_user = await get_web_current_user(request, db)
    if current_user is None:
        return RedirectResponse(url="/web/login", status_code=303)

    context = get_common_context(request, current_user)

    try:
        # 获取情感分析统计数据
        # 这里需要根据实际的数据模型来查询
        context.update({
            "sentiment_types": [],
            "chart_data": {}
        })

    except Exception as e:
        context.update({
            "error": f"获取情感分析数据失败: {str(e)}"
        })

    return jinja_templates.TemplateResponse("sentiment-analysis.html", context)


@web_router.get("/compliance-analysis", response_class=HTMLResponse)
async def compliance_analysis_page(
    request: Request,
    db: Session = Depends(get_db)
):
    """规范性分析页面"""
    # 获取当前用户
    current_user = await get_web_current_user(request, db)
    if current_user is None:
        return RedirectResponse(url="/web/login", status_code=303)

    context = get_common_context(request, current_user)

    try:
        # 获取规范性分析统计数据
        # 这里需要根据实际的数据模型来查询
        context.update({
            "compliance_types": [],
            "chart_data": {}
        })

    except Exception as e:
        context.update({
            "error": f"获取规范性分析数据失败: {str(e)}"
        })

    return jinja_templates.TemplateResponse("compliance-analysis.html", context)


@web_router.get("/duplicate-analysis", response_class=HTMLResponse)
async def duplicate_analysis_page(
    request: Request,
    db: Session = Depends(get_db)
):
    """重复分析页面"""
    # 获取当前用户
    current_user = await get_web_current_user(request, db)
    if current_user is None:
        return RedirectResponse(url="/web/login", status_code=303)

    context = get_common_context(request, current_user)

    try:
        # 获取重复分析统计数据
        # 这里需要根据实际的数据模型来查询
        context.update({
            "duplicate_stats": {},
            "similarity_distribution": {},
            "cluster_data": {}
        })

    except Exception as e:
        context.update({
            "error": f"获取重复分析数据失败: {str(e)}"
        })

    return jinja_templates.TemplateResponse("duplicate-analysis.html", context)


@web_router.get("/coordinate-analysis", response_class=HTMLResponse)
async def coordinate_analysis_page(
    request: Request,
    db: Session = Depends(get_db)
):
    """坐标分析页面"""
    # 获取当前用户
    current_user = await get_web_current_user(request, db)
    if current_user is None:
        return RedirectResponse(url="/web/login", status_code=303)
    
    context = get_common_context(request, current_user)
    
    try:
        # 获取坐标数据
        # 这里需要根据实际的数据模型来查询
        context.update({
            "coordinates": [],
            "map_data": {}
        })
        
    except Exception as e:
        context.update({
            "error": f"获取坐标分析数据失败: {str(e)}"
        })
    
    return jinja_templates.TemplateResponse("coordinate-analysis.html", context)


@web_router.get("/key-issues", response_class=HTMLResponse)
async def key_issues_page(
    request: Request,
    db: Session = Depends(get_db)
):
    """重点问题分析页面"""
    # 获取当前用户
    current_user = await get_web_current_user(request, db)
    if current_user is None:
        return RedirectResponse(url="/web/login", status_code=303)
    
    context = get_common_context(request, current_user)
    
    try:
        # 获取重点问题数据
        # 这里需要根据实际的数据模型来查询
        context.update({
            "issues": [],
            "trends": {}
        })
        
    except Exception as e:
        context.update({
            "error": f"获取重点问题分析数据失败: {str(e)}"
        })
    
    return jinja_templates.TemplateResponse("key-issues.html", context)






@web_router.get("/report-generation", response_class=HTMLResponse)
async def report_generation_page(
    request: Request,
    db: Session = Depends(get_db)
):
    """报告生成页面"""
    # 获取当前用户
    current_user = await get_web_current_user(request, db)
    if current_user is None:
        return RedirectResponse(url="/web/login", status_code=303)
    
    context = get_common_context(request, current_user)
    
    try:
        # 获取报告列表
        reports = db.query(Report).order_by(desc(Report.created_at)).limit(10).all()
        
        # 获取报告模板
        from models.report import ReportTemplate
        report_templates = db.query(ReportTemplate).filter(
            ReportTemplate.is_active == True
        ).all()
        
        context.update({
            "reports": reports,
            "report_templates": report_templates
        })
        
    except Exception as e:
        context.update({
            "error": f"获取报告生成数据失败: {str(e)}"
        })
    
    return jinja_templates.TemplateResponse("report-generation.html", context)


@web_router.get("/ai-reports", response_class=HTMLResponse)
async def ai_reports_page(
    request: Request,
    db: Session = Depends(get_db)
):
    """AI智能报告生成页面"""
    # 获取当前用户
    current_user = await get_web_current_user(request, db)
    if current_user is None:
        return RedirectResponse(url="/web/login", status_code=303)
    
    context = get_common_context(request, current_user)
    
    try:
        # 获取最近的AI报告
        from models.report import Report, ReportType
        ai_reports = db.query(Report).filter(
            Report.config.isnot(None),
            Report.config.like('%"type": "ai_%')
        ).order_by(desc(Report.created_at)).limit(10).all()
        
        context.update({
            "ai_reports": ai_reports
        })
        
    except Exception as e:
        context.update({
            "error": f"获取AI报告数据失败: {str(e)}"
        })
    
    return jinja_templates.TemplateResponse("ai-reports.html", context)


@web_router.get("/account-management", response_class=HTMLResponse)
async def account_management_page(
    request: Request,
    db: Session = Depends(get_db)
):
    """账号管理页面"""
    # 获取当前用户
    current_user = await get_web_current_user(request, db)
    if current_user is None:
        return RedirectResponse(url="/web/login", status_code=303)
    
    # 检查管理员权限
    if not current_user.is_superuser:
        return RedirectResponse(url="/web/analysis-results", status_code=303)
    
    context = get_common_context(request, current_user)
    
    try:
        # 这里可以添加一些初始化数据
        context.update({
            "page_title": "账号管理",
            "page_description": "管理系统用户账户和权限"
        })
        
    except Exception as e:
        context.update({
            "error": f"加载账号管理页面失败: {str(e)}"
        })
    
    return jinja_templates.TemplateResponse("account-management.html", context)


@web_router.get("/system-settings", response_class=HTMLResponse)
async def system_settings_page(
    request: Request,
    db: Session = Depends(get_db)
):
    """系统设置页面"""
    # 获取当前用户
    current_user = await get_web_current_user(request, db)
    if current_user is None:
        return RedirectResponse(url="/web/login", status_code=303)
    
    # 检查管理员权限
    if not current_user.is_superuser and not current_user.has_permission("system:manage"):
        return RedirectResponse(url="/web/analysis-results", status_code=303)
    
    context = get_common_context(request, current_user)
    
    try:
        # 获取系统配置数据
        context.update({
            "page_title": "系统设置",
            "page_description": "系统基础配置和参数设置"
        })
        
    except Exception as e:
        context.update({
            "error": f"获取系统设置数据失败: {str(e)}"
        })
    
    return jinja_templates.TemplateResponse("system-settings.html", context)


@web_router.get("/security", response_class=HTMLResponse)
async def security_page(
    request: Request,
    db: Session = Depends(get_db)
):
    """安全管理页面"""
    # 获取当前用户
    current_user = await get_web_current_user(request, db)
    if current_user is None:
        return RedirectResponse(url="/web/login", status_code=303)
    
    # 检查管理员权限
    if not current_user.is_superuser and not current_user.has_permission("system:manage"):
        return RedirectResponse(url="/web/analysis-results", status_code=303)
    
    context = get_common_context(request, current_user)
    
    try:
        # 获取基本的安全统计信息
        from services.security_service import get_security_statistics
        security_stats = await get_security_statistics()
        
        context.update({
            "security_stats": security_stats
        })
        
    except Exception as e:
        context.update({
            "error": f"获取安全统计数据失败: {str(e)}"
        })
    
    return jinja_templates.TemplateResponse("security.html", context)


# 错误页面
@web_router.get("/error", response_class=HTMLResponse)
async def error_page(
    request: Request,
    message: str = "发生错误",
    db: Session = Depends(get_db)
):
    """错误页面"""
    # 获取当前用户（可选，错误页面可能不需要登录）
    current_user = await get_web_current_user(request, db)
    context = get_common_context(request, current_user)
    context.update({
        "error_message": message
    })
    return jinja_templates.TemplateResponse("error.html", context)


# 数据源加载测试页面
@web_router.get("/test-datasource", response_class=HTMLResponse)
async def test_datasource_page(
    request: Request,
    db: Session = Depends(get_db)
):
    """数据源加载功能测试页面"""
    # 检查用户是否已登录
    current_user = await get_web_current_user(request, db)
    
    context = get_common_context(request, current_user)
    return jinja_templates.TemplateResponse("test-datasource.html", context)


# Web路由根路径处理器
@web_router.get("/", response_class=HTMLResponse)
async def web_root_page(
    request: Request,
    db: Session = Depends(get_db)
):
    """Web根路径处理器，智能跳转到dashboard或登录页面"""
    # 检查用户是否已登录
    current_user = await get_web_current_user(request, db)
    
    if current_user:
        # 已登录，直接跳转到分析结果页面
        return RedirectResponse(url="/web/analysis-results", status_code=302)
    else:
        # 未登录，跳转到登录页面
        return RedirectResponse(url="/web/login", status_code=302)


